package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.domain.AppGoodsInfo;
import com.ruoyi.app.domain.AppGoodsOrders;
import com.ruoyi.app.domain.bo.AppGoodsOrdersBo;
import com.ruoyi.app.domain.bo.AppGoodsOrdersData;
import com.ruoyi.app.domain.vo.AppAddressVo;
import com.ruoyi.app.domain.vo.AppGoodsOrdersVo;
import com.ruoyi.app.domain.vo.AppGoodsVo;
import com.ruoyi.app.mapper.AppGoodsOrdersMapper;
import com.ruoyi.app.service.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OrderNumUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * APP商城订单Service业务层处理
 *
 * @author heike
 * @date 2023-03-02
 */
@RequiredArgsConstructor
@Service
public class AppGoodsOrdersServiceImpl implements IAppGoodsOrdersService {

    private final AppGoodsOrdersMapper baseMapper;
    private final IAppAddressService iAppAddressService;
    private final IAppGoodsService iAppGoodsService;
    private final IAppGoodsInfoService appGoodsInfoService;
    private final IAppGoodsCartService iAppGoodsCartService;

    /**
     * 查询APP商城订单
     */
    @Override
    public AppGoodsOrdersVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public AppGoodsOrdersVo queryOrderNo(String orderNo) {
        LambdaQueryWrapper<AppGoodsOrders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppGoodsOrders::getOrderNo, orderNo);
        return baseMapper.selectVoOne(wrapper);
    }

    /**
     * 查询APP商城订单列表
     */
    @Override
    public TableDataInfo<AppGoodsOrdersVo> queryPageList(AppGoodsOrdersBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppGoodsOrders> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(AppGoodsOrders::getId);
        Page<AppGoodsOrdersVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询APP商城订单列表
     */
    @Override
    public List<AppGoodsOrdersVo> queryList(AppGoodsOrdersBo bo) {
        LambdaQueryWrapper<AppGoodsOrders> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppGoodsOrders> buildQueryWrapper(AppGoodsOrdersBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppGoodsOrders> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, AppGoodsOrders::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNo()), AppGoodsOrders::getOrderNo, bo.getOrderNo());
        lqw.eq(StringUtils.isNotBlank(bo.getExternalOrderNo()), AppGoodsOrders::getExternalOrderNo, bo.getExternalOrderNo());
        lqw.eq(bo.getTotalPrice() != null, AppGoodsOrders::getTotalPrice, bo.getTotalPrice());
        lqw.like(StringUtils.isNotBlank(bo.getTakeName()), AppGoodsOrders::getTakeName, bo.getTakeName());
        lqw.eq(StringUtils.isNotBlank(bo.getTakePhone()), AppGoodsOrders::getTakePhone, bo.getTakePhone());
        lqw.eq(StringUtils.isNotBlank(bo.getTakeAddress()), AppGoodsOrders::getTakeAddress, bo.getTakeAddress());
        lqw.eq(bo.getPayTime() != null, AppGoodsOrders::getPayTime, bo.getPayTime());
        lqw.like(StringUtils.isNotBlank(bo.getShipName()), AppGoodsOrders::getShipName, bo.getShipName());
        lqw.eq(StringUtils.isNotBlank(bo.getShipCode()), AppGoodsOrders::getShipCode, bo.getShipCode());
        lqw.eq(bo.getShipTime() != null, AppGoodsOrders::getShipTime, bo.getShipTime());
        lqw.eq(bo.getShipPrice() != null, AppGoodsOrders::getShipPrice, bo.getShipPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getPayType()), AppGoodsOrders::getPayType, bo.getPayType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AppGoodsOrders::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), AppGoodsOrders::getType, bo.getType());
        lqw.eq(bo.getCancelTime() != null, AppGoodsOrders::getCancelTime, bo.getCancelTime());
        return lqw;
    }

    /**
     * 新增APP商城订单
     */
    @Override
    public Boolean insertByBo(AppGoodsOrdersBo bo) {
        AppGoodsOrders add = BeanUtil.toBean(bo, AppGoodsOrders.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改APP商城订单
     */
    @Override
    public Boolean updateByBo(AppGoodsOrdersBo bo) {
        AppGoodsOrders update = BeanUtil.toBean(bo, AppGoodsOrders.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 修改APP商城订单
     */
    @Override
    public Boolean updateByVo(AppGoodsOrdersVo vo) {
        AppGoodsOrders update = BeanUtil.toBean(vo, AppGoodsOrders.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }


    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppGoodsOrders entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除APP商城订单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppGoodsOrdersBo createOrder(AppGoodsOrdersData param) {
        AppGoodsOrdersBo order = new AppGoodsOrdersBo();
        List<AppGoodsInfo> orderGoodsList = new ArrayList<>();
        String orderNo = OrderNumUtils.getInstance().generateOrderNo();
        AppAddressVo userAddress = iAppAddressService.queryById(param.getAddressId());
        String takeAddress = userAddress.getCity() + userAddress.getCityDetails();
        order.setTakeName(userAddress.getNickName());
        order.setTakePhone(userAddress.getMobile());
        order.setTakeAddress(takeAddress);
        String[] goodIds = param.getGoodsIdStr().split(",");
        String[] numbers = param.getBuyNumStr().split(",");
        BigDecimal total = BigDecimal.ZERO;
        for (int i = 0; i < goodIds.length; i++) {
            if (StringUtils.isBlank(goodIds[i])) {
                continue;
            }
            BigDecimal price = BigDecimal.ZERO;
            Long goodsId = Long.valueOf(goodIds[i]);
            int buyNum = Integer.parseInt(numbers[i]);
            AppGoodsVo goods = iAppGoodsService.queryById(goodsId);
            if (Objects.nonNull(goods)) {
                price = goods.getGoodsPrice().multiply(new BigDecimal(buyNum)).setScale(2);
            }
            total = total.add(price);
            AppGoodsInfo orderGoods = new AppGoodsInfo();
            orderGoods.setOrderNo(orderNo);
            orderGoods.setGoodsId(goodsId);
            orderGoods.setNumber(buyNum);
            orderGoods.setGoodsPrice(goods.getGoodsPrice());
            orderGoodsList.add(orderGoods);
        }
        if (orderGoodsList.size() > 0) {
            appGoodsInfoService.inserts(orderGoodsList);
        }
        if (StringUtils.isNotBlank(param.getIsFromCart())
            && param.getIsFromCart().equals(Constants.FAIL)) {
            String[] split = param.getShopCartIds().split(",");
            ArrayList<Long> ids = new ArrayList<>();
            Arrays.stream(split).forEach(e -> {
                if (StringUtils.isNotBlank(e)) {
                    ids.add(Long.valueOf(e));
                }
            });
            iAppGoodsCartService.deleteWithValidByIds(ids, true);
        }
        order.setOrderNo(orderNo);
        order.setTotalPrice(total);
        order.setRemark(param.getRemark());
        order.setStatus(Constants.SUCCESS);
        order.setType("1");
        order.setUserId(param.getUserId());
        order.setCreateTime(DateUtils.getNowDate());
        insertByBo(order);
        return order;
    }

    @Override
    public Boolean cancelOrder(AppGoodsOrdersVo ordersVo) {
        LambdaUpdateWrapper<AppGoodsOrders> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AppGoodsOrders::getId, ordersVo.getId()).set(AppGoodsOrders::getStatus, "4");
        return baseMapper.update(null, wrapper) > 0;
    }
}
